<template>
    <div style="margin-top: 30px" v-loading="fullFormLoading">
        <el-form label-width="14%" style="display: grid;gap: 16px;grid-template-columns: repeat(3, 1fr);">
            <el-form-item label="实例ID">
                <el-input v-model="searchFormInstanceId" placeholder="实例ID"></el-input>
            </el-form-item>
            <el-form-item label="表单版本">
                <el-select v-model="currentVersion" placeholder="表单版本" @change="versionSelectChange()">
                    <el-option :label="item.innerName" :value="item.version" v-for="item in versionList" :key="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item v-for="(item, index) in formConditionList" :label="item.labelName">
                <component :is="item.component" :isEdit="false" :isInstanceSearch="true" :properties="item"/>
            </el-form-item>
        </el-form>
        <div class="formSubmitButton">
            <el-button @click="addFormInstanceCondition()">添加条件</el-button>
            <el-button type="primary" :loading="searchLoading" @click="searchClick()">查 询</el-button>
        </div>
    </div>

    <div style="display: flex; justify-content: right">
        <el-button type="primary" style="margin-right: 20px" @click="addFormInstance()">添加实例</el-button>
    </div>

    <div style="padding-left: 20px; padding-right: 20px; margin-top: 20px" v-loading="formTableLoading">
        <el-table
            :data="formInstanceDataList"
            style="width: 100%;"
            row-key="id"
            border
            :stripe="true"
            :show-overflow-tooltip="true"
            class="tableContainer"
            max-height="70vh"
            v-if="reloadTable"
        >
            <el-table-column v-for="item in tableItemList" :key="item.prop" :prop="item.prop" :label="item.label" />

            <el-table-column align="center" width="200px">
                <template #header>
                    <span>操 作</span>
                </template>
                <template #default="scope">
                    <el-button size="small" type="success" @click="handleUpdateInstance(scope.$index, scope.row)">编 辑</el-button>
                    <el-button type="danger" size="small" @click="handleDeleteInstance(scope.$index, scope.row)">删 除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <div style="padding-right: 20px;">
        <el-pagination
            v-model:current-page="pageIndex"
            v-model:page-size="pageSize"
            layout="prev, pager, next, jumper, sizes, total"
            :background="true"
            :total="recordCount"
            style="margin-top: 30px;width: 100%;display: flex; align-items: center;justify-content: right"
            @change="changePage"
            :page-sizes="[10, 20, 30, 40, 50]"
        />
    </div>

    <div>
        <el-dialog
            v-model="isShowDrawer"
            title="添加表单实例"
            width="80%"
            :show-close="false"
            :close-on-click-modal="false"
        >
            <el-form label-width="10%" :style="formColStyle" style="margin-top: 30px">
                <el-form-item v-for="(item, index) in formBuildList" :label="item.labelName">
                    <component :is="item.component" :isEdit="false" :isInstanceSearch="false" :properties="item"/>
                </el-form-item>
            </el-form>
            <div class="formSubmitButton" style="margin-top: 30px">
                <el-button @click="cancelAddFormInstance()">取消</el-button>
                <el-button @click="commitAddFormInstance()" :loading="addFormInstanceLoading" type="primary">提交</el-button>
            </div>
        </el-dialog>
    </div>

    <div>
        <el-dialog
            v-model="isUpdateShowDrawer"
            title="修改表单实例"
            width="80%"
            :show-close="false"
            :close-on-click-modal="false"
        >
            <el-form label-width="10%" :style="formColStyle" style="margin-top: 30px">
                <el-form-item v-for="(item, index) in formBuildList" :label="item.labelName">
                    <component :is="item.component" :isEdit="false" :isInstanceSearch="false" :properties="item"/>
                </el-form-item>
            </el-form>
            <div class="formSubmitButton" style="margin-top: 30px">
                <el-button @click="cancelUpdateFormInstance()">取消</el-button>
                <el-button @click="commitUpdateFormInstance()" :loading="updateFormInstanceLoading" type="primary">提交</el-button>
            </div>
        </el-dialog>
    </div>

    <div>
        <el-dialog
            v-model="isDeleteShowDrawer"
            title="删除表单实例"
            width="20%"
            :show-close="false"
            :close-on-click-modal="false"
        >
            <span>是否确认删除？</span>
            <div class="formSubmitButton" style="margin-top: 30px">
                <el-button @click="cancelDeleteFormInstance()">取消</el-button>
                <el-button @click="commitDeleteFormInstance()" :loading="deleteInstanceLoading" type="primary">提交</el-button>
            </div>
        </el-dialog>
    </div>

    <div>
        <el-dialog
            v-model="isConditionShowDrawer"
            title="编辑表单实例条件"
            :show-close="false"
            :width="600"
            :close-on-click-modal="false"
        >
            <el-transfer class="formSubmitButton" :data="conditionSourceList" v-model="conditionTargetList"
                         :titles="['表单组件', '条件']"/>
            <div class="formSubmitButton" style="margin-top: 30px">
                <el-button @click="cancelFormInstanceCondition()">取消</el-button>
                <el-button @click="commitFormInstanceCondition()" :loading="conditionInstanceLoading" type="primary">提交</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import YwuFormInput from "@/views/bpmn/form/component/YwuFormInput";
import {
    createFormInstance, createFormInstanceCondition, deleteFormInstance, queryFormInstanceCondition,
    queryFormInstanceList,
    queryVersionInfo,
    queryVersionList,
    updateFormInstance
} from "@/request/flow";
import {ElNotification} from "element-plus";

export default {
    name: "FormInstanceList",
    components: {
        YwuFormInput
    },
    data() {
        return {
            currentVersion: 0,
            versionList: [],
            globalProperties: {
                colNum: 1
            },
            formBuildList: [],
            searchFormInstanceId: "",
            formInstanceDataList: [],
            tableItemList: [],
            isShowDrawer: false,
            formColStyle: "",
            reloadTable: true,
            pageIndex: 1,
            pageSize: 10,
            recordCount: 0,
            addFormInstanceLoading: false,
            updateFormInstanceLoading: false,
            deleteInstanceLoading: false,
            isUpdateShowDrawer: false,
            formInstanceId: "",
            isDeleteShowDrawer: false,
            searchLoading: false,
            formConditionList: [],
            isConditionShowDrawer: false,
            conditionInstanceLoading: false,
            conditionSourceList: [],
            conditionTargetList: [],
            fullFormLoading: false,
            formTableLoading: false,
        }
    },
    methods: {
        buildTableItem() {
            this.tableItemList = [];
            this.tableItemList[0] = {label: "实例ID", prop: "id"};
            this.tableItemList[1] = {label: "实例版本", prop: "formVersion"};
            for (let index = 0; index < this.formBuildList.length; index++) {
                let itemInfo = this.formBuildList[index]
                this.tableItemList[index + 2] = {label: itemInfo.labelName, prop: itemInfo.id};
            }
        },
        addFormInstance() {
            let res = "display: grid;gap: 16px;"
            let repeat = `grid-template-columns: repeat(${this.globalProperties.colNum}, 1fr);`
            this.formColStyle = res + repeat;
            this.isShowDrawer = true;
            for (let index = 0; index < this.formBuildList.length; index++) {
                this.formBuildList[index].bindValue = "";
            }
        },
        cancelAddFormInstance() {
            this.isShowDrawer = false;
        },
        commitAddFormInstance() {
            this.addFormInstanceLoading = true;
            // 构建实例json信息
            let formInstanceJson = {};
            for (let index = 0; index < this.formBuildList.length; index++) {
                let itemInfo = this.formBuildList[index];
                if (!itemInfo.bindValue) {
                    break;
                }
                formInstanceJson[itemInfo.id] = itemInfo.bindValue;
                if (typeof formInstanceJson[itemInfo.id] !== 'string') {
                    formInstanceJson[itemInfo.id] = "" + formInstanceJson[itemInfo.id]
                }
            }
            // 构建对象
            let formId = this.$route.query.id;
            let param = {
                formId: formId,
                formVersion: this.currentVersion,
                formInstanceJson: JSON.stringify(formInstanceJson)
            }
            createFormInstance(param).then(res => {
                if (res.code === "200") {
                    ElNotification({
                        title: 'Success',
                        message: res.message,
                        type: 'success',
                    })
                    // 查询分页列表
                    let queryParam = this.getQueryParam()
                    queryFormInstanceList(queryParam).then(res => {
                        this.formInstanceDataList = []
                        for (let index = 0; index < res.data.dataList.length; index++) {
                            let item = res.data.dataList[index]
                            let jsonStr = item.formInstanceJson;
                            let jsonInfo = JSON.parse(jsonStr);
                            jsonInfo.id = item.id;
                            jsonInfo.formVersion = item.formVersion;
                            this.formInstanceDataList.push(jsonInfo);
                        }
                        this.pageIndex = res.data.pageIndex;
                        this.pageSize = res.data.pageSize;
                        this.recordCount = res.data.recordCount;
                        this.isShowDrawer = false;
                        this.addFormInstanceLoading = false;
                    }).catch(res => {
                        this.isShowDrawer = false;
                        this.addFormInstanceLoading = false;
                    })
                }
            }).catch(res => {
                this.isShowDrawer = false;
                this.addFormInstanceLoading = false;
            })
        },
        queryBuildInfoAndInstanceInfo() {
            this.fullFormLoading = true;
            this.formTableLoading = true
            let formId = this.$route.query.id;
            queryVersionInfo({resourceId: formId, version: this.currentVersion}).then(queryVersionRes => {
                if (queryVersionRes.code === "200") {
                    let formJson = queryVersionRes.data.formJson
                    // 序列化json
                    let jsonInfo = JSON.parse(formJson);
                    this.globalProperties = jsonInfo.globalProperties
                    this.formBuildList = jsonInfo.componentJson
                    // 构建表单内容信息
                    this.buildTableItem();
                    // 查询分页列表
                    let queryParam = this.getQueryParam()
                    queryFormInstanceList(queryParam).then(res => {
                        this.formInstanceDataList = []
                        for (let index = 0; index < res.data.dataList.length; index++) {
                            let item = res.data.dataList[index]
                            let jsonStr = item.formInstanceJson;
                            let jsonInfo = JSON.parse(jsonStr);
                            jsonInfo.id = item.id;
                            jsonInfo.formVersion = item.formVersion;
                            this.formInstanceDataList.push(jsonInfo);
                        }
                        this.pageIndex = res.data.pageIndex;
                        this.pageSize = res.data.pageSize;
                        this.recordCount = res.data.recordCount;
                        this.formTableLoading = false;
                    }).catch(res => {
                        this.formTableLoading = false;
                    })
                }
            }).catch(res => {
                this.formTableLoading = false;
            })
            queryFormInstanceCondition({formId: formId, formVersion: this.currentVersion}).then(res => {
                this.formConditionList = []
                if (res.code === "200") {
                    if (res.data === null) {
                        this.formConditionList = []
                    } else {
                        let formConditionJson = res.data.formConditionJson
                        // 序列化json
                        this.formConditionList = JSON.parse(formConditionJson);
                    }
                }
                this.fullFormLoading = false;
            }).catch(res => {
                this.fullFormLoading = false;
            })
        },
        versionSelectChange() {
            this.queryBuildInfoAndInstanceInfo();
        },
        handleUpdateInstance(index, row) {
            let res = "display: grid;gap: 16px;"
            let repeat = `grid-template-columns: repeat(${this.globalProperties.colNum}, 1fr);`
            this.formColStyle = res + repeat;
            this.isUpdateShowDrawer = true;
            this.formInstanceId = row.id;
            let rowKeys = Object.keys(row);
            // 遍历每一个build对象，将当前行中的值映射到bindValue中
            for (let index = 0; index < this.formBuildList.length; index++) {
                let item = this.formBuildList[index];
                for (let rowIndex = 0; rowIndex < rowKeys.length; rowIndex++) {
                    if (item.id === rowKeys[rowIndex]) {
                        // 当前对象的id和当前行中的prop一致，则将当前value值绑定到bindValue中
                        item.bindValue = row[rowKeys[rowIndex]]
                        break;
                    }
                }
            }
        },
        handleDeleteInstance(index, row) {
            this.formInstanceId = row.id;
            this.isDeleteShowDrawer = true;
        },
        cancelUpdateFormInstance() {
            this.isUpdateShowDrawer = false;
        },
        commitUpdateFormInstance() {
            this.updateFormInstanceLoading = true;
            // 构建实例json信息
            let formInstanceJson = {};
            for (let index = 0; index < this.formBuildList.length; index++) {
                let itemInfo = this.formBuildList[index];
                if (!itemInfo.bindValue) {
                    break;
                }
                formInstanceJson[itemInfo.id] = itemInfo.bindValue;
                if (typeof formInstanceJson[itemInfo.id] !== 'string') {
                    formInstanceJson[itemInfo.id] = "" + formInstanceJson[itemInfo.id]
                }
            }
            // 构建对象
            let formId = this.$route.query.id;
            let param = {
                id: this.formInstanceId,
                formId: formId,
                formVersion: this.currentVersion,
                formInstanceJson: JSON.stringify(formInstanceJson)
            }
            updateFormInstance(param).then(res => {
                if (res.code === "200") {
                    ElNotification({
                        title: 'Success',
                        message: res.message,
                        type: 'success',
                    })
                    // 查询分页列表
                    let queryParam = this.getQueryParam()
                    queryFormInstanceList(queryParam).then(res => {
                        this.formInstanceDataList = []
                        for (let index = 0; index < res.data.dataList.length; index++) {
                            let item = res.data.dataList[index]
                            let jsonStr = item.formInstanceJson;
                            let jsonInfo = JSON.parse(jsonStr);
                            jsonInfo.id = item.id;
                            jsonInfo.formVersion = item.formVersion;
                            this.formInstanceDataList.push(jsonInfo);
                        }
                        this.pageIndex = res.data.pageIndex;
                        this.pageSize = res.data.pageSize;
                        this.recordCount = res.data.recordCount;
                        this.isUpdateShowDrawer = false;
                        this.updateFormInstanceLoading = false;
                    }).catch(res => {
                        this.isUpdateShowDrawer = false;
                        this.updateFormInstanceLoading = false;
                    })
                }
            }).catch(res => {
                this.isUpdateShowDrawer = false;
                this.updateFormInstanceLoading = false;
            })
        },
        cancelDeleteFormInstance() {
            this.isDeleteShowDrawer = false
        },
        commitDeleteFormInstance() {
            this.deleteInstanceLoading = true;
            let param = {
                id: this.formInstanceId
            }
            deleteFormInstance(param).then(res => {
                if (res.code === "200") {
                    ElNotification({
                        title: 'Success',
                        message: res.message,
                        type: 'success',
                    })
                    let formId = this.$route.query.id;
                    // 查询分页列表
                    let queryParam = this.getQueryParam()
                    queryFormInstanceList(queryParam).then(res => {
                        this.formInstanceDataList = []
                        for (let index = 0; index < res.data.dataList.length; index++) {
                            let item = res.data.dataList[index]
                            let jsonStr = item.formInstanceJson;
                            let jsonInfo = JSON.parse(jsonStr);
                            jsonInfo.id = item.id;
                            jsonInfo.formVersion = item.formVersion;
                            this.formInstanceDataList.push(jsonInfo);
                        }
                        this.pageIndex = res.data.pageIndex;
                        this.pageSize = res.data.pageSize;
                        this.recordCount = res.data.recordCount;
                        this.deleteInstanceLoading = false;
                        this.isDeleteShowDrawer = false;
                    }).catch(res => {
                        this.deleteInstanceLoading = false;
                        this.isDeleteShowDrawer = false;
                    })
                }
            }).catch(res => {
                this.deleteInstanceLoading = false;
                this.isDeleteShowDrawer = false;
            })
        },
        getQueryParam() {
            let formId = this.$route.query.id;
            let param = {
                pageInfo: {
                    pageIndex: this.pageIndex,
                    pageSize: this.pageSize
                },
                id: this.searchFormInstanceId,
                formId: formId,
                formVersion: this.currentVersion
            }
            let formInstanceJson = [];
            for (let index = 0; index < this.formConditionList.length; index++) {
                let itemInfo = this.formConditionList[index];
                if (!itemInfo.searchValue) {
                    continue;
                }
                let searchValue = itemInfo.searchValue;
                if (typeof searchValue !== 'string') {
                    searchValue = "" + searchValue
                }
                formInstanceJson.push({
                    id: "$.\"" + itemInfo.id + "\"",
                    value: searchValue
                })
            }
            param.extendFormFieldList = formInstanceJson
            return param;
        },
        searchClick() {
            this.searchLoading = true;
            // 查询数据
            let param = this.getQueryParam()
            queryFormInstanceList(param).then(res => {
                this.formInstanceDataList = []
                for (let index = 0; index < res.data.dataList.length; index++) {
                    let item = res.data.dataList[index]
                    let jsonStr = item.formInstanceJson;
                    let jsonInfo = JSON.parse(jsonStr);
                    jsonInfo.id = item.id;
                    jsonInfo.formVersion = item.formVersion;
                    this.formInstanceDataList.push(jsonInfo);
                }
                this.pageIndex = res.data.pageIndex;
                this.pageSize = res.data.pageSize;
                this.recordCount = res.data.recordCount;
                this.searchLoading = false;
            }).catch(res => {
                this.searchLoading = false;
            })
        },
        cancelFormInstanceCondition() {
            this.isConditionShowDrawer = false;
        },
        commitFormInstanceCondition() {
            this.conditionInstanceLoading = true;
            // 调用接口保存条件信息
            let formId = this.$route.query.id;
            let param = {
                formId: formId,
                formVersion: this.currentVersion,
            }
            let formConditionJsonInfo = []
            // 将target中的对象添加到参数中
            for (let index = 0; index < this.conditionTargetList.length; index++) {
                let itemId = this.conditionTargetList[index]
                for (let innerIndex = 0; innerIndex < this.formBuildList.length; innerIndex++) {
                    if (this.formBuildList[innerIndex].id === itemId) {
                        formConditionJsonInfo.push(this.formBuildList[innerIndex])
                        break;
                    }
                }
            }
            param.formConditionJson = JSON.stringify(formConditionJsonInfo);
            // 调用方法创建表单条件
            createFormInstanceCondition(param).then(res => {
                if (res.code === "200") {
                    ElNotification({
                        title: 'Success',
                        message: res.message,
                        type: 'success',
                    })
                    queryFormInstanceCondition({formId: formId, formVersion: this.currentVersion}).then(res => {
                        this.formConditionList = []
                        if (res.code === "200") {
                            if (res.data === null) {
                                this.formConditionList = []
                            } else {
                                let formConditionJson = res.data.formConditionJson
                                // 序列化json
                                this.formConditionList = JSON.parse(formConditionJson);
                            }
                        }
                        this.conditionInstanceLoading = false;
                        this.isConditionShowDrawer = false;
                    }).catch(res => {
                        this.conditionInstanceLoading = false;
                        this.isConditionShowDrawer = false;
                    })
                }
            }).catch(res => {
                this.conditionInstanceLoading = false;
                this.isConditionShowDrawer = false;
            })
        },
        addFormInstanceCondition() {
            this.conditionSourceList = []
            this.conditionTargetList = []
            for (let index = 0; index < this.formBuildList.length; index++) {
                this.conditionSourceList.push({
                    key: this.formBuildList[index].id,
                    label: this.formBuildList[index].labelName
                })
            }
            // 构建出当前已经存在的所有id列表
            for (let index = 0; index < this.formConditionList.length; index++) {
                this.conditionTargetList.push(this.formConditionList[index].id)
            }
            this.isConditionShowDrawer = true;
        },
        changePage() {
            // 查询数据
            let param = this.getQueryParam()
            queryFormInstanceList(param).then(res => {
                this.formInstanceDataList = []
                for (let index = 0; index < res.data.dataList.length; index++) {
                    let item = res.data.dataList[index]
                    let jsonStr = item.formInstanceJson;
                    let jsonInfo = JSON.parse(jsonStr);
                    jsonInfo.id = item.id;
                    jsonInfo.formVersion = item.formVersion;
                    this.formInstanceDataList.push(jsonInfo);
                }
                this.pageIndex = res.data.pageIndex;
                this.pageSize = res.data.pageSize;
                this.recordCount = res.data.recordCount;
            })
        }
    },
    mounted() {
        this.fullFormLoading = true;
        this.formTableLoading = true
        // 根据表单ID查询当前表单最新版本以及表单的构建信息
        let formId = this.$route.query.id;
        queryVersionList({id: formId}).then(res => {
            if (res.code === "200") {
                let dataInfo = res.data;
                if (dataInfo.length === 0 || (dataInfo.length === 1 && dataInfo[0].version === 0)) {
                    ElNotification({
                        title: 'Error',
                        message: "不存在可用发布版本",
                        type: 'error',
                    })
                    this.fullFormLoading = false;
                    this.formTableLoading = false
                    return
                }
                // 获取最新版本
                if (dataInfo[0].version === 0) {
                    this.currentVersion = dataInfo[1].version;
                } else {
                    this.currentVersion = dataInfo[0].version;
                }
                // 获取版本下拉列表
                let tempList = dataInfo
                if (tempList[0].version === 0) {
                    tempList.splice(0, 1);
                }
                this.versionList = tempList;
                // 为每个版本对象添加一个内置名称
                for (let index = 0; index < this.versionList.length; index++) {
                    this.versionList[index].innerName = "版本" + this.versionList[index].version;
                }
                // 查询表单对应的构建信息以及表单对应的实例信息
                this.queryBuildInfoAndInstanceInfo();
            }
        }).catch(res => {
            this.fullFormLoading = false;
            this.formTableLoading = false
        })
    }
}
</script>

<style scoped lang="less">
.formSubmitButton {
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>